//Filemanager.cpp
//@author A0101038Y
#include "FileManager.h"
FileManager& FileManager::getInstance(string fileName) {
	static FileManager instance(fileName);
	return instance;
}
FileManager::FileManager(string fileName):_fileName(fileName)
{
}

FileManager::~FileManager(void)
{
}

void FileManager::updateFile(){//updates file with the entries vector
	_outFile.open(_fileName.c_str(), ios::trunc);
	writingToFile();
	_outFile.close();
}

void FileManager::loadLineToVector() {
	std::string lineContent;
	ostringstream outStream;
	for(int i=0; i<Entry::NUM_ATTRIBUTES; i++) {
		std::getline(_inFile, lineContent);
		outStream << endl << lineContent;
	}
	//Entry* newEntry = EntryManager::fromString(outStream.str());
	//if(!newEntry.isEmpty()) {
		//_entries.push_back(newEntry);
	//}
}
void FileManager::loadEntries(){//Loads file contents into entry vector
	_inFile.open(_fileName.c_str(), std::fstream::app);
	_entries.clear();
	string entryType;
	while(getline(_inFile, entryType)) {
		loadEntryType(entryType);
		if(entryType == CommonUtils::ENTRY_TYPE_TASK) {
			string content;
			string newcontent;
			loadContentTask(content, newcontent);
			//cout << content << endl;
			Task * newTask=new Task(Task::fromString(content));
			_entries.push_back(newTask);
		} else if(entryType == CommonUtils::ENTRY_TYPE_EVENT) {
			string content;
			string newcontent;
			loadContentEvent(content, newcontent);
			//cout << content << endl;
			Event * newEvent=new Event(Event::fromString(content));
			_entries.push_back(newEvent);
		}
	}
	_inFile.close();
}
vector<Entry*> FileManager::getEntries(){//returns the loaded vector
	loadEntries();
	return _entries;
}
void FileManager::updateFromVector(vector<Entry*> input) {
	_entries.clear();
	_entries = input;
	updateFile();
}
void FileManager::writingToFile(){
	for(int i=0; i<_entries.size() ; i++) {
		_outFile << _entries[i]->toString();
	}
}
void FileManager::loadEntryType(string &entryType){
	while(entryType != CommonUtils::ENTRY_TYPE_TASK && entryType != CommonUtils::ENTRY_TYPE_EVENT) {
			getline(_inFile, entryType);
		}
}
void FileManager::loadContentTask(string &content, string &newcontent){
	for(int i=1; i<= Task::NUM_ATTRIBUTES; i++) {
		getline(_inFile, newcontent);
		content += newcontent + "\n";
	}
}
void FileManager::loadContentEvent(string &content, string &newcontent){
	for(int i=1; i<= Event::NUM_ATTRIBUTES; i++) {
		getline(_inFile, newcontent);
		content += newcontent +"\n";
	}
}